# encoding: utf-8
# 项目名称： day02
# @File  : city.py
# @Author: sun hao
# @Desc :  城市列表数据展示

from django.shortcuts import render
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from app01 import models


def city_list(request):
    # 获取并验证分页参数
    try:
        page = max(1, int(request.GET.get('page', 1)))
    except ValueError:
        page = 1

    try:
        limit = max(1, min(100, int(request.GET.get('limit', 10))))
    except ValueError:
        limit = 10

    # 查询数据并排序
    queryset = models.City.objects.all().order_by('-id')

    # 使用Django的Paginator进行分页
    paginator = Paginator(queryset, limit)
    try:
        data_list = paginator.page(page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    context = {
        'MEDIA_URL': settings.MEDIA_URL,
        'data_list': data_list,
        'totals': paginator.count,
        'current_page': data_list.number,
        'page_size': limit,
        'total_pages': paginator.num_pages,
    }

    return render(request, 'city/list.html', context)
